//
//  YWGropButtonView.m
//  maintain
//
//  Created by 郑想 on 16/6/17.
//  Copyright © 2016年 ewin. All rights reserved.
//
#define kYWPictureViewBaseTag 100
#define kYWPictrueWH floorf(SCREEN_WIDTH/4 - 5) - 7
#define kYWPictureMargin 10
#define kYWMaxPictureCount 6
#define kYWPictureMaxCol(count) ((count == 4) ? 2 : 3)
#import "YWGropButtonView.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "UIView+Extension.h"
#import "YWattachment.h"
#import "YWResourceManager.h"
#import "YWAttachmentManager.h"
//#import "YWAlertView.h"
#import "Masonry.h"

@implementation YWGropButtonView

- (void)initWithGroupItems:(NSArray *)groupItems withshotContrain:(NSLayoutConstraint *)shotContraint{
    _attachments = groupItems;
    self.clipsToBounds = YES;
    if (self.subviews) {
        [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
        }];
    }
    self.hidden = NO;
//    根据内容改变高
    NSUInteger count = groupItems.count;
    CGFloat buttonHigt = (SCREEN_WIDTH - 70)/3;
    for (int i = 0; i < count; i++) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = kYWPictureViewBaseTag + i;
        [button addTarget:self action:@selector(handlePictuceViewTapEvent:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.titleLabel.font = kContentFont;
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
        
        YWattachment *attachment = groupItems[i];
        //根据不同的附件，显示不同的图标
        NSString *typemName = [[attachment.downLoadUrl componentsSeparatedByString:@"."] lastObject];
        [button setImage:[self imageWithType:typemName] forState:UIControlStateNormal];
        [button setTitle:attachment.attachmentName forState:UIControlStateNormal];
        CGFloat imageSize = 40;
        CGSize buttonLabelSize = CGSizeMake(kYWPictrueWH-10, 20);
        CGFloat heightGap = (kYWPictrueWH-imageSize-buttonLabelSize.height)/3;
        button.imageEdgeInsets = UIEdgeInsetsMake(heightGap,(kYWPictrueWH - imageSize)/2,0,0);
        button.titleEdgeInsets = UIEdgeInsetsMake(imageSize +heightGap*2,  (kYWPictrueWH - buttonLabelSize.width) / 2  -  imageSize, 0, 0);
        button.frame = CGRectMake(i%3 * (5 + buttonHigt), i/3 * (buttonHigt + 5), buttonHigt, buttonHigt);
        
        if (count == 0) {
            [self mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(@0).priorityHigh();
            }];
        } else if (count <= 3) {
            [self mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(@((SCREEN_WIDTH - 70)/3 + 5)).priorityHigh();
            }];
        } else {
            [self mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(@((SCREEN_WIDTH - 70)/3 * 2 + 10)).priorityHigh();
            }];
        }

        [self addSubview:button];
    }
}

-(void)handlePictuceViewTapEvent:(UIButton*)sender{
    __block NSInteger tag = sender.tag-kYWPictureViewBaseTag;
    __block YWattachment *attachment = nil;
    if (tag<=self.attachments.count) {
        attachment = (YWattachment *)self.attachments[tag];
        if (attachment.localName.length>0) {
            if ([self.delegate respondsToSelector:@selector(handleAttachment:)]) {
                [self.delegate handleAttachment:attachment];
            }
        }else{
            NSString *fileSize = [YWCommonTool getFileSize:attachment.fileSize*1024];
            NSString *tip = [NSString stringWithFormat:@"文件大小: %@,是否下载 (建议您在wifi环境下下载)",fileSize];
            UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:tip preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [sender setTitle:@"下载中" forState:UIControlStateNormal];
                NSString *typemName = [[attachment.downLoadUrl componentsSeparatedByString:@"."] lastObject];
                NSString* documentName = attachment.attachmentName?:[NSString stringWithFormat:@"%@.%@", [YWCommonTool randStringId],typemName];
                NSString *fullPath = [[YWResourceManager shareManager] fileCachePathFromResourcePath:documentName];
                [[YWAttachmentManager shareManager] downloadFile:attachment.downLoadUrl toFilePath:fullPath progressBlock:nil completeBlock:^(BOOL success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (success) {
                            //保存全路径到数据库
                            attachment.localName = documentName;
                            BOOL save = [[YWAttachmentManager shareManager] updateAttachmenLocalNameWithAttachment:attachment];
                            if (save) {
                                [[NSNotificationCenter defaultCenter] postNotificationName:KPostNoticeAttachmentReflashNotification object:attachment];
                                [sender setTitle:@"下载成功" forState:UIControlStateNormal];
                            }else{
                                [YWCommonTool showTextHUDWithContent:@"下载失败，请重试"];
                                [sender setTitle:@"下载失败" forState:UIControlStateNormal];
                            }
                        }else{
                            [YWCommonTool showTextHUDWithContent:@"下载失败，请重试"];
                            [sender setTitle:@"下载失败" forState:UIControlStateNormal];
                        }
                    });
                }];
                
            }]];
            [self.viewController presentViewController:alertController animated:YES completion:nil];
        }
    }
}

- (UIImage*)imageWithType:(NSString*)type{
    UIImage *image = nil;
    if ([type compare:@"doc" options:NSCaseInsensitiveSearch] == NSOrderedSame|| [type compare:@"docx" options:NSCaseInsensitiveSearch]== NSOrderedSame) {
        image = [UIImage imageNamed:@"attachment_word"];
    }else if ([type compare:@"ppt" options:NSCaseInsensitiveSearch]== NSOrderedSame|| [type compare:@"pptx" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_ppt"];
    }else if ([type compare:@"pdf" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_pdf"];
    }else if ([type compare:@"xls" options:NSCaseInsensitiveSearch]== NSOrderedSame||[type compare:@"xlsx" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_excel"];
    }else if ([type compare:@"txt" options:NSCaseInsensitiveSearch]== NSOrderedSame){
        image = [UIImage imageNamed:@"attachment_txt"];
    }
    else {
        image = [UIImage imageNamed:@"attachment_unknow"];
    }
    return image;
}

- (UIViewController*)viewController
{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

@end
